<?php
// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------
namespace app\user\model;
use think\Db;
/**
 * 提现账户
 * Class WithdrawAccount
 * @package app\user\model
 * @author 似水星辰 [ 2630481389@qq.com ]
 * @created 2019/9/13 20:50
 */
class WithdrawAccount extends \think\Model{
    
    protected $table = '__USER_WITHDRAW_ACCOUNT__';
    
        
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    
    /**
     * 获取列表
     * @param mixed $map
     * @param mixed $order
     * @return mixed
     */
     public static function getList($map = [],$order = []) {
        return self::view('user_withdraw_account', true)
            ->view("user", 'user_nickname,head_img,mobile', 'user.id=user_withdraw_account.user_id', 'left')    
            ->where($map)
            ->order($order)
            ->paginate();
    }
    
    
     /**
     * 添加提现账户
     * @author 晓风 2021-8-12
     * @param int $user_id 会员ID
     * @param array $param 参数
     * @param bool $isOne 当前类型是否不可重复
     * @return bool|string
     * @throws \Exception
     */
    public static  function addInfo(int $user_id,array $param,bool $isOne = true){        
        
        Db::startTrans();
        try {
            $validate = \think\facade\App::instance()->validate(\app\user\validate\WithdrawAccount::class);
            $res = $validate->check($param);
            if(!$res){
                throw new \Exception($validate->getError());
            }
            if(!$param["qrcode"] && !$param["account_id"]){
                throw new \Exception("二维码或账户至少填一样");
            }    
            $param["user_id"] = $user_id;
            $info = self::where(['user_id' =>  $user_id, 'account_type' => $param['account_type']])->find();     
            if ($info && $isOne) {
                self::where(['user_id' =>  $user_id])->update(['is_default' => 0]);//这是伪命题不能判断
                $res =  self::where(['id' => $info['id']])->update($param);
                if (false === $res) {
                    throw new \Exception('绑定失败');
                }
            } else {
                $param['status'] = 1;
                $res = self::create($param);
                if (!$res) {
                    throw new \Exception('绑定失败');
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return  $e->getMessage();
        }
        return true;
    }
    
    
}
